package com.shaiMiMi;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/*
这是一个用来辅助读取一个整包数据的类
 */
public class TcpReadHelper {
	private Socket m_Socket = null;
	private long m_dataSize = 0;
	private long m_dataSize_HaveRead = 0;
	private byte[] m_packDataArray = null;

	public TcpReadHelper(Socket socket){
		m_Socket = socket;
	}

	//返回值代表是否完全读完一个完整包
	public boolean Read(){
		try {
			InputStream inputStream = m_Socket.getInputStream();
			if (0 == m_dataSize)	//读取数据包总大小
			{
				if(inputStream.available() < 8 )	//数据不足包头大小
					return false;

				byte[] sizeByte = new byte[8];
				inputStream.read(sizeByte, 0, 8);
				m_dataSize = DataTypeChangeHelper.byteToLong(sizeByte);
				m_dataSize -= 8; //扣除包头的实际包大小
				int iDataSize = (int)m_dataSize;
				m_packDataArray = new byte[iDataSize];
			}

			if (m_dataSize > 0)
			{
				long remainderDataSize = m_dataSize - m_dataSize_HaveRead;	//剩余需要读取的字节数
				long bateAvailable = inputStream.available();
				if ( remainderDataSize <= bateAvailable )
				{
					inputStream.read(m_packDataArray, (int)m_dataSize_HaveRead, (int)remainderDataSize);
					return true;
				}
				else
				{
					inputStream.read(m_packDataArray, (int)m_dataSize_HaveRead, (int)bateAvailable);
					m_dataSize_HaveRead += bateAvailable;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}

	public void	Reset(){
		m_dataSize = 0;
		m_dataSize_HaveRead = 0;
		m_packDataArray = null;
	}

	public byte[] GetPackDataArray(){
		return m_packDataArray;
	}

	public Socket GetSocket(){
		return m_Socket;
	}
}
